package com.dycn.posdashboard.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.dycn.posdashboard.action.JspProxyAction;
import com.dycn.posdashboard.action.LoginAction;
import com.dycn.posdashboard.data.JsonResponseData;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 用户是否登录拦截器
 * @author gongqiyi
 *
 */
public class LoginInterceptor extends AbstractInterceptor {

    /**
     * <pre>
     * 
     * </pre>
     */
    private static final long serialVersionUID = 1L;

    public static final String LOGIN_KEY  = "LoginName";

    public static final String LOGIN_PAGE = "global.login";
    
    protected final Log log = LogFactory.getLog(getClass());

    private JsonResponseData<String> jsonResponseData;
    
    public JsonResponseData<String> getJsonResponseData() {
		return jsonResponseData;
	}
	public void setJsonResponseData(JsonResponseData<String> jsonResponseData) {
		this.jsonResponseData = jsonResponseData;
	}
	
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        
        // 对LoginAction不做该项拦截
        Object action = actionInvocation.getAction();
        if (action instanceof LoginAction
        		||action instanceof JspProxyAction) {
            log.debug("exit check enh login, because this is login action.");
            return actionInvocation.invoke();
        }

        // 确认Session中是否存在LOGIN
        
        HttpServletRequest request = ServletActionContext.getRequest();  
        String sessionId=request.getSession().getId();
        log.debug("确认Session中是否存在LOGIN :session Id:"+sessionId);
        
        Map<String, Object> session = actionInvocation.getInvocationContext().getSession();
        String login = (String) session.get(LOGIN_KEY);
        if (login != null && login.length() > 0) {
            // 存在的情况下进行后续操作。
            //log.debug("already login!");
            return actionInvocation.invoke();
        } else {
            // 否则终止后续操作，返回LOGIN
    		jsonResponseData=new JsonResponseData<String>();
    		jsonResponseData.setSuccess(false);
    		jsonResponseData.setResultCode(JsonResponseData.SESSION_TIMEOUT);
    		jsonResponseData.setMsg("no login, forward login page!");
    		jsonResponseData.setData("");
            ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_FORBIDDEN);   
            log.debug("no login, forward login page!");
            return LOGIN_PAGE;
        }
    }
}